package com.manage.entity;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.data.jpa.domain.Specification;
import org.springframework.util.StringUtils;


@Entity
@Table(name="t_courses")
public class Course {              //课程实体类
	private Long id;	
	private String coursesType;
	private String coursesName;
	private int hours;
	private String introduction;
	
	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	public Long getId() {
		return id;
	}

	public String getCoursesType() {
		return coursesType;
	}

	public String getCoursesName() {
		return coursesName;
	}

	public int getHours() {
		return hours;
	}

	public String getIntroduction() {
		return introduction;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public void setCoursesType(String coursesType) {
		this.coursesType = coursesType;
	}

	public void setCoursesName(String coursesName) {
		this.coursesName = coursesName;
	}

	public void setHours(int hours) {
		this.hours = hours;
	}

	public void setIntroduction(String introduction) {
		this.introduction = introduction;
	}
	
	public static Specification<Course> getSpecification( final Course course)
	{
		Specification<Course> spec = new Specification<Course>() {
			public Predicate toPredicate(Root<Course> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				//1.Predicate查询条件集合
				 List<Predicate> list = new ArrayList<Predicate>(); 
				 
				//2.根据 QueryDTO数据字段的值进行判断以及条件的组装
				 if(null != course && !StringUtils.isEmpty(course.getCoursesName())) {
					 Predicate  p1 =  cb.like(root.get("coursesName").as(String.class),"%"+ course.getCoursesName()+ "%");
					 list.add(p1);
				 }
				 if(null != course && !StringUtils.isEmpty(course.getCoursesType())) {
					 Predicate  p2 =  cb.like(root.get("coursesType").as(String.class),"%"+ course.getCoursesType()+ "%");
					 list.add(p2);
				 }
				 //3.Predicate查询条件集合的 size 创建对应的Predicate查询条件数组
				 Predicate[] p = new Predicate[list.size()];  
				 //4.CriteriaBuilder的and 函数组装 查询条件数组
				 return cb.and(list.toArray(p));  
			}
		};
		return spec;	
	}
}
